import { dayjs } from 'element-plus'
import type { App, Plugin } from 'vue'

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any
  comp.install = (app: App) => {
    app.component(comp.name || comp.displayName, comp)
    if (alias) {
      app.config.globalProperties[alias] = component
    }
  }
  return component as T & Plugin
}

/** 白屏时间 */
export const blankTime = () => {
  const t: any = performance.getEntriesByType('navigation')[0]
  const value = (t?.domInteractive ?? t?.domLoading ?? 0) - t?.fetchStart
  return `${value.toLocaleString()}ms`
}

/**
 * 时间戳转日期时间
 * @param {number} date 时间戳
 * @param {string} template 转换格式
 * @returns
 */
export const formatUnix = (
  date: number,
  template: string = 'YYYY-MM-DD HH:mm:ss'
): string => {
  return date ? dayjs.unix(date).format(template) : '-'
}

/// 计算时间差
export const formatDiff = ({
  begin = '0',
  end = '0',
  diff = '0'
}: {
  begin?: number | string
  end?: number | string
  diff?: number | string
} = {}): string => {
  let temp = Number(end ?? '0') - Number(begin ?? '0')
  if (diff) {
    temp = Number(diff)
  }
  let hh: any = ~~(temp / 3600)
  let mm: any = 0
  let ss: any = 0

  if (temp < 0) return '-'
  if (hh > 0) {
    mm = ~~((temp - hh * 3600) / 60)
    if (mm > 0) {
      ss = temp - hh * 3600 - mm * 60
    } else {
      ss = temp - hh * 3600
    }
  } else {
    mm = ~~(temp / 60)
    if (mm > 0) {
      ss = temp - mm * 60
    } else {
      ss = temp
    }
  }
  if (hh === 0 && mm === 0 && ss === 0) {
    return '-'
  } else {
    if (hh < 10) {
      hh = `0${hh}`
    }
    if (mm < 10) {
      mm = `0${mm}`
    }
    if (ss < 10) {
      ss = `0${ss}`
    }
    return `${hh}:${mm}:${ss}`
  }
}
/**秒转时分秒 */
export const secToTime = (time: number) => {
  let result: string = '-'
  if (time) {
    const day = Math.floor(time / 3600 / 24)
    const hour = Math.floor((time / 3600) % 24)
    const min = Math.floor(time / 60) % 60
    result = day ? day + '天' : hour ? hour + '小时' : min + '分钟'
  }
  return result
}
//对比当前时间 判断是否过期
export const getTimeIsExpires = (time: number) => {
  const now = dayjs().unix()
  return !!(time > 0 && now - time >= 0)
}
/**
 * 去空格，去空行
 * @param value string
 * @returns
 */
export function getTrimValue(value: string) {
  return value
    .split(/\n/)
    .map(v => v.trim())
    .filter(Boolean)
}
/**
 * dataURLtoBlob
 * @param dataUrl 文件流string
 * @returns
 */
function dataURLtoBlob(dataUrl: string) {
  const arr = (dataUrl ?? '').split(',')
  const mime = arr[0].match(/:(.*?);/)![1]
  const str = window.atob(arr[1])
  let n = str.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = str.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}
/**
 * base64下载
 * @param text 文件内容
 * @param fileName 文件名
 * @param type 文件类型
 */
export function useDownloadByBase64(
  text: string,
  _fileName: string,
  type = 'application/x-tar'
) {
  const at = `data:${type};base64,${text}`
  const blob = dataURLtoBlob(at)

  const href = window.URL.createObjectURL(blob)
  const aLink = document.createElement('a')
  aLink.href = href
  aLink.download = '下载文件'
  aLink.style.display = 'none'
  document.body.appendChild(aLink)
  aLink.click()
  document.body.removeChild(aLink)
  window.URL.revokeObjectURL(href)
}
/**
 * zip
 * @param content 文件内容
 * @param fileName 文件名
 */
export function useDownloadZipByBase64(content: string, fileName: string) {
  const str = window.atob(content)
  let n = str.length
  const arr8 = new Uint8Array(n)
  while (n--) {
    arr8[n] = str.charCodeAt(n)
  }
  // 创建一个 Blob 对象
  const blob = new Blob([arr8], { type: 'application/zip' })
  // 创建一个 URL 对象
  const url = URL.createObjectURL(blob)
  // 创建一个链接元素并设置相关属性
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  // 将链接元素添加到页面中并触发点击事件
  document.body.appendChild(link)
  link.click()
  // 清理 URL 对象
  URL.revokeObjectURL(url)
  // ToastUtils.success('下载成功')
}

//字符串转txt下载
export function useDownloadTxt(content: string, fileName: string = 'log') {
  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const aLink = document.createElement('a')
  aLink.href = url
  aLink.download = `${fileName}.txt`
  aLink.click()
  URL.revokeObjectURL(url)
}
// 复制
export const copy = (value: string | number) => {
  const textarea = document.createElement('textarea')
  textarea.readOnly = true
  textarea.style.position = 'absolute'
  textarea.style.left = '-9999px'
  textarea.value = value.toString()
  document.body.appendChild(textarea)
  textarea.select()
  const result = document.execCommand('Copy')
  if (result) {
    ToastUtils.success('复制成功')
  }
  document.body.removeChild(textarea)
}
